package com.ruge.system.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.ruge.common.properties.UploadProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020/3/21  9:30
 * 描述 ：
 *
 * @author Administrator
 */
@Service

public class FastDFSClient {

    @Resource
    private FastFileStorageClient fastFileStorageClient;
    @Resource
    private UploadProperties uploadProperties;
    /**
     * 文件上传
     *
     * @param file 上传的文件
     * @return
     */
    public String uploadFile(MultipartFile file) throws IOException {
        String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        Set<MetaData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MetaData("width", "120"));
        metaDataSet.add(new MetaData("heigth", "120"));
        StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), extension, metaDataSet);
        return uploadProperties.getBaseUrl()+storePath.getFullPath();
    }

    /**
     * 文件下载
     *
     * @param fileUrl
     * @return
     */
    public byte[] downloadFile(String fileUrl) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        return fastFileStorageClient.downloadFile(group, path, downloadByteArray);
    }
}
